/************************************************************************
Copyright 2003, 2004, 2005, 2006, 2007, 2008 Grid Technology Research Center,
National Institute of Advanced Industrial Science and Technology.

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
************************************************************************/

package jp.aist.gtrc.plus.scheduler.specific.pbs.batch;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import jp.aist.gtrc.plus.scheduler.specific.pbs.batch.actor.PBSBatchActor;
import jp.aist.gtrc.plus.scheduler.specific.pbs.batch.reply.BatchReply;
import jp.aist.gtrc.plus.scheduler.specific.pbs.batch.reply.BatchReplyNull;
import jp.aist.gtrc.plus.scheduler.specific.pbs.batch.request.BatchRequest;
import jp.aist.gtrc.plus.scheduler.specific.pbs.batch.request.BatchRequestType;
import jp.aist.gtrc.plus.scheduler.specific.pbs.util.PBSException;

import org.apache.log4j.Logger;



public class PBSBatchServer extends PBSBatch implements Runnable{

	private final ServerSocket serverSocket;
	private final PBSBatchActor actor;
	private boolean finishNow = false;

	protected static final  Logger logger = Logger.getLogger(PBSBatchServer.class);

	public PBSBatchServer(int port, PBSBatchActor actor) throws IOException{

		this.serverSocket = new ServerSocket(port);
		this.actor = actor;

	}

	public void run(){

		logger.debug("PBSBatchServer Started at " + serverSocket.toString());

		while (finishNow == false) {
			Socket s = null;
			try {
				s = serverSocket.accept();
				processRequest(s);
			} catch (IOException e) {
				if (finishNow)
					break;
				logger.warn("PBSBatchServer failed", e);
			} finally {
				if (s != null) {
					try {
						s.close();
					} catch (IOException e) {
						// ignore
					}
				}
			}
		}

		logger.debug("PBSBatchServer Exited at " + serverSocket.toString());

	}

	private void processRequest(Socket socket) throws IOException{

		String rawData = receiveData(socket);
		BatchRequest request = null;
		BatchReply reply = null;

		try {
			request = decoder.getDecodedRequest(rawData);
		} catch (PBSException e) {
			logger.warn("Invalid BatchRequest", e);
			reply = new BatchReplyNull(e.getErrorCode());
		}

		if (request != null)
			reply = actor.operate(request, socket);

		if (reply != null) {
			encoder.reset();
			reply.encode(encoder);
			sendData(socket, encoder.getEncodedData());
		} else {
			// Only Disconnect doesn't need reply
			assert(request.getRequestType() == BatchRequestType.Disconnect);
		}

	}

	public void finish() {

		finishNow = true;
		try {
			serverSocket.close();
		} catch (IOException e) {
			// ignore
		}

	}

}
